package com.yycx.app.provider.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zyf
 */
@Slf4j
public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    private BearerTokenExtractor tokenExtractor;

    private RedisTokenStore redisTokenStore;

    public LogoutSuccessHandler() {

    }
    public LogoutSuccessHandler(RedisTokenStore redisTokenStore, BearerTokenExtractor tokenExtractor) {
        this.redisTokenStore = redisTokenStore;
        this.tokenExtractor = tokenExtractor;
        // 重定向到原地址
        this.setUseReferer(true);
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try {
            // 解密请求头
            authentication = tokenExtractor.extract(request);
            if (authentication != null && authentication.getPrincipal() != null) {
                String tokenValue = authentication.getPrincipal().toString();
                log.debug("revokeToken tokenValue:{}", tokenValue);
                // 移除token
                redisTokenStore.removeAccessToken(redisTokenStore.readAccessToken(tokenValue));
            }
        } catch (Exception e) {
            log.error("revokeToken error:{}", e);
        }
        super.onLogoutSuccess(request, response, authentication);
    }
}